<!--
 * @Author: 夏郑兴 971348024@qq.com
 * @Date: 2022-05-10 12:01:51
 * @LastEditors: 夏郑兴 971348024@qq.com
 * @LastEditTime: 2022-05-30 17:10:41
 * @FilePath: /gitee-project/task-distribution-admin/src/views/servicePages/projectManagement/components/batchImportDialog.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="dialog-content">
    <el-dialog
      :title="title"
      v-model="visible"
      :close-on-click-modal="false"
      width="600px"
      :before-close="handleClose"
    >
      <div
        id="detail-center"
        style="
          overflow: hidden;
          overflow-y: auto;
          height: 50vh;
          max-height: 50vh;
        "
      >
        <div v-if="showUpload">
          <div class="detail-center-title">
            首次导入请点击下载
            <el-button v-if="uploadObj.downloadObj && uploadObj.downloadObj.name" type="text" class="download-temp" @click="downloadFile"
              >{{ uploadObj.downloadObj.name }}</el-button>
            按表格内格式填写信息，再将表格上传，将完导入操作
          </div>
          <div class="detail-center-upload">
            <div>
              <div>上传文件：<span v-if="uploadList.length === 0">-</span></div>
              <div v-if="uploadList.length === 0" class="upload-type-tip">仅支持Excel文件上传</div>
            </div>
            <div class="upload-list" v-for="(item, i) in uploadList" :key="i">
              {{ item.name }}
              <i class="el-icon-delete" @click="delUpload(i)"></i>
            </div>
          </div>
          <div v-if="adminInfo.admin_type === 2 && !adminInfo.action_permissions.includes('2')" class="dialog-btns">
            <el-button type="primary" @click="uploadFileClick">上传文件</el-button>
          </div>
          <div v-else class="dialog-btns">
            <el-upload
              v-if="uploadList.length === 0"
              ref="upload"
              :multiple="uploadObj.multiple"
              :limit="uploadObj.limit"
              :accept="uploadObj.accept"
              :show-file-list="false"
              :auto-upload="true"
              :http-request="uploadFileFun"
            >
              <template #default>
                <el-button type="primary" @click="uploadFileClick">上传文件</el-button>
              </template>
            </el-upload>
            <el-button v-else type="primary" @click="batchImportReqFun"
              >批量导入</el-button
            >
          </div>
        </div>
        <!-- 批量导入loading状态 -->
        <div v-if="uploading" class="uploading-icon">
          <div>
            <div class="uploading-icon-loading"><i class="el-icon-loading"></i></div>
            <div>批量导入中，请稍后</div>
          </div>
        </div>
        <!-- 批量导入成功状态 -->
        <div v-if="successShow" class="uploading-success">
          <div>
            <div class="uploading-success-icon"><i class="el-icon-success"></i> 导入成功</div>
            <div class="uploading-success-info">共识别导入 {{resData.total_rows}} 条数据</div>
            <div>
              <el-button class="uploading-success-close" @click="handleSuccessClose">关闭</el-button>
            </div>
          </div>
        </div>
        <!-- 批量导入失败状态 -->
        <div v-if="errorShow" class="uploading-error">
          <div>
            <div class="uploading-error-icon"><i class="el-icon-error"></i> 导入失败</div>
            <!-- 接口500处理 -->
            <div v-if="resData.message != ''" style="text-align:center;" >
              <div class="uploading-error-info"  style="color:red;">{{resData.message}}</div>
              <el-button v-if="resData.message != ''" @click="resetUpload">重新上传</el-button>
            </div>
            <div class="uploading-error-info" v-else>共识别导入 {{resData.total_rows}} 条数据, 剩余 {{resData.fail_rows}} 条因格式或数据问题识别失败！</div>
          </div>
          <!-- 接口200 -->
          <div v-if="!resData.message">
            <div class="table-error-data">
              <div class="table-tr table-th">
                <div class="table-sort">
                  序号
                </div>
                <div class="table-info">
                  错误原因
                </div>
              </div>
              <div class="table-tr" v-for="(item, i) in errorData" :key="i">
                <div class="table-sort">
                  {{item.number}}
                </div>
                <div class="table-info">
                  {{item.reason}}
                </div>
              </div>
            </div>
            <div class="import-tip">
              注意：识别错误的数据将不会导入进系统，注意识别报错信息，修改错误后操作重新导入。
            </div>
            <div class="download-btn">
              <!-- <el-button type="text" @click="downloadErrorFile">下载报错文件</el-button> -->
            </div>
            <div class="reset-btn">
              <!-- <el-button @click="resetUpload">重新上传</el-button> -->
              <!-- <el-button type="primary">继续导入</el-button> -->
              <el-button class="uploading-success-close" @click="handleSuccessClose">关闭</el-button>
            </div>
          </div>
          
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { batchImportReq } from "@/api/service/user.ts";
import { useStore } from "vuex";

export default defineComponent({
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: null,
    },
    title: {
      type: String,
      default: "",
    },
    uploadObj: {
      type: Object,
      default: {
        fileType: [".xls", ".xlsx"],
        accept: ".xls, .xlsx", // 文件上传类型
        multiple: false, // 是否支持多选
        url: "", // 批量导入接口地址
        downloadObj: {
          name: '',
          url: ''
        }, // excel模板下载地址
      },
    },
  },
  setup(props, ctx) {
    const store = useStore();
    const adminInfo = reactive(store.state.user.adminInfo);
    // 下载文件
    const downloadFile = () => {
      // 1:查看权限, 2:上传权限, 3:下载权限
      // 上传权限的判断
      // if (adminInfo.admin_type === 2 && !adminInfo.action_permissions.includes('3')) {
      //   ElMessage.error("温馨提示：对不起，您暂无下载权限。");
      //   return;
      // }
      let url = props.uploadObj.downloadObj.url
      window.open(url)
    }
    // 上传按钮
    const uploadFileClick = () => {
      // 1:查看权限, 2:上传权限, 3:下载权限
      // 上传权限的判断
      if (adminInfo.admin_type === 2 && !adminInfo.action_permissions.includes('2')) {
        ElMessage.error("温馨提示：对不起，您暂无上传权限。");
        return;
      }
    }
    // 取消
    const handleClose = () => {
      ctx.emit("closeUploadDialog");
    };
    // 上传数据
    const uploadList = ref([]); // 点击上传的暂存文件
    const uploadFormData: any = ref(null); // 点击上传的暂存文件

    const uploadFileFun = (fileInfo: any) => {
      // 1:查看权限, 2:上传权限, 3:下载权限
      // 上传权限的判断
      if (adminInfo.admin_type === 2 && !adminInfo.action_permissions.includes('2')) {
        ElMessage.error("温馨提示：对不起，您暂无上传权限。");
        return;
      }
      console.log(fileInfo);
      let file = fileInfo.file;
      const fileType = props.uploadObj.fileType || [".xlsx", ".xls"];
      const type = file.name.substr(file.name.lastIndexOf(".")).toLowerCase();
      // 上传类型限制
      if (!fileType.includes(type)) {
        let type = fileType.join(",");
        ElMessage.error(`温馨提示：只支持${type}格式的文件`);
        return;
      }

      let formData = new FormData();
      formData.append("file", file);
      uploadFormData.value = formData;
      uploadList.value.push({
        name: file.name,
        // formData: formData
      });
    };
    // loading状态
    const uploading = ref(false);
    const showUpload = ref(true);
    const successShow = ref(false);
    const errorShow = ref(false);
    // 上传失败数据
    const errorData = ref([]);
    const resData = reactive({
      fail_rows: '',
      success_rows: '',
      total_rows: '',
      message: '', // code:500提示信息
    });

    // 批量导入按钮
    const batchImportReqFun = () => {
      debugger
      uploading.value = true;
      showUpload.value = false;
      let data = {
        url: props.uploadObj.url,
      };
      batchImportReq(data, uploadFormData.value).then((res: any) => {
        if (res.code === 200) {
          if(props.uploadObj.type == 'team'){
             ctx.emit("refreshTable");
             return
          }
          if(props.uploadObj.type == 'status'){
             ctx.emit("closeUploadDialog",true);
             return
          }
          let data = res.data
          errorData.value = data.err_list; // 错误数据
          resData.fail_rows = data.fail_rows; // 失败记录数
          resData.success_rows = data.success_rows; // 成功记录数
          resData.total_rows = data.total_rows;
          resData.message = ''; // 错误信息提示

          // 根据状态判断导入成功或失败
          if (data.fail_rows === 0) {
            // 导入成功
            successShow.value = true;
            errorShow.value = false;
          } else {
            successShow.value = false;
            errorShow.value = true;
          }
          // 成功后刷新表格
          ctx.emit("refreshTable");
        } else {
          resData.message = res.message; // 错误信息提示
        }
      })
      .catch((e: any) => {
        successShow.value = false;
        errorShow.value = true;

        resData.message = e.message; // 错误信息提示
      })
      .finally(() => {
        uploading.value = false;
      });
    };
    // 删除上传的项目
    const delUpload = (i: Number) => {
      uploadList.value.splice(i, 1);
      uploadFormData.value = null;
    };
    // 上传成功后的关闭按钮 
    const handleSuccessClose = () => {
      ctx.emit("closeUploadDialog");
    }
    // 下载报错文件
    const downloadErrorFile = () => {

    }
    // 重新上传
    const resetUpload = () => {
      successShow.value = false;
      errorShow.value = false;
      uploadList.value = [];
      uploadFormData.value = null;
      uploading.value = false;
      errorData.value = [];

      // 显示上传 
      showUpload.value = true;
    }


    return {
      store,
      adminInfo,
      handleClose,
      uploadFileFun,
      batchImportReqFun,
      uploadList,
      uploadFormData,
      delUpload,
      uploading,
      showUpload,
      successShow,
      errorShow,
      errorData,
      resData,
      handleSuccessClose,
      downloadErrorFile,
      resetUpload,
      downloadFile,
      uploadFileClick
    };
  },
});
</script>

<style lang="scss" scoped>
.dialog-content {
  .detail-center-title {
    font-size: 16px;
    .download-temp {
      font-size: 16px;
    }
  }
  .detail-center-upload {
    font-size: 16px;
    margin-top: 20px;
    display: flex;
    height: 30vh;
    .upload-type-tip{
      padding-top: 10px;
    }
    .upload-list {
      margin-bottom: 10px;
      .el-icon-delete {
        margin-left: 10px;
      }
    }
  }
  .dialog-btns {
    text-align: center;
  }
  .uploading-icon{
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    top: -20px;
    .uploading-icon-loading{
      text-align: center;
      margin-bottom: 20px;;
    }
    i{
      font-size: 70px;
    }
  }
  .uploading-success{
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    width: 100%;
    text-align:center;
    
    .uploading-success-icon{
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 20px;
      font-size: 24px;
      color: #000;
      .el-icon-success{
        font-size: 40px;
        color:greenyellow;
        margin-right: 10px;

      }
    }
    .uploading-success-info{
      margin-bottom: 50px;
      font-size: 16px;
    }
  }
  .uploading-success-close{
    padding: 0 40px;
    margin-top: 20px;
  }
  .uploading-error{
    .uploading-error-icon{
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 20px;
      font-size: 24px;
      color: #000;
      .el-icon-error{
        font-size: 40px;
        color:rgb(255, 89, 47);
        margin-right: 10px;

      }
    }
    .uploading-error-info{
      margin-bottom: 20px;
      font-size: 16px;
      text-align: center;
    }
    .table-error-data{
      border: 1px solid #ccc;
      border-radius: 10px;
      padding: 5px;
      width: 80%;
      margin: 0 auto;
      .table-tr{
        display: flex;
        justify-content: left;
        align-items: center;
        border-bottom: 1px solid #ccc;
        padding: 20px 0;
        .table-sort{
          width: 30%;
          text-align: center;
        }
        .table-info{
          width: 70%;
        }
      }
      .table-th{
        font-size: 16px;
        font-weight: bold;

      }
    }
    .table-tr:last-child{
      border-bottom: none;
    }
    .import-tip{
      font-size: 14px;
      font-weight: bold;
      width: 80%;
      margin: 10px auto;
    }
    .download-btn{
      width: 80%;
      margin: 10px auto;
    }
    .reset-btn{
      text-align: center;
    }
  }
  
  
}
</style>
